package leetbook.math;

public class Solution172 {

    public static void main(String[] args) {
        Solution172 s = new Solution172();
        int n = 5;
        System.out.println(s.factorial(n));
        System.out.println(s.trailingZeroes(n));
    }

    /**
     * n!结尾0的个数
     * 思路：n!的质因子分解中有多少对2和5就有多少0
     */
    public int trailingZeroes(int n) {
        int num_2 = 0, num_5 = 0;
        for (int i = 2; i <= n; i++) {
            int j = i;
            while ((j&1)==0){
                num_2++;
                j>>=1;
            }
            while ((j%5)==0){
                num_5++;
                j/=5;
            }
        }
        return Math.min(num_2,num_5);
    }

    /**
     * n!结尾0的个数
     * 思路：n!的质因子分解中2肯定比5多，只要统计5的个数
     * 复杂度：nlogn
     */
    public int trailingZeroes1(int n) {
        int num = 0;
        for (int i = 5; i <= n; i+=5) {
            int j = i;
            while ((j%5)==0){
                num++;
                j/=5;
            }
        }
        return num;
    }

    /**
     * 1..n每次用5除，不能整除的就被筛掉，能整除的记一次因子数
     * 重复筛选，直到没有数字剩下
     * 复杂度：logn
     */
    public int trailingZeroes2(int n) {
        int num = 0;
        while (n!=0){
            n /= 5;
            num += n;
        }
        return num;
    }

    public long factorial(int n){
        return n==1?1:factorial(n-1)*n;
    }
}
